package com.tao.content.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;

import javax.crypto.spec.SecretKeySpec;

/**
 * <p>
 *
 * </p>
 *
 * @author taohongrun
 * @since 2024/11/25
 */
@Configuration
public class TokenConfig {

    private static final String ISSUER_URI = "http://127.0.0.1:63070/auth";

    @Bean
    public JwtDecoder jwtDecoder() {
        // 直接使用认证服务器配置的jwks端点
        return NimbusJwtDecoder.withJwkSetUri(ISSUER_URI + "/oauth2/jwks")
                .build();
    }

    @Bean
    public JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities"); // 匹配token中的authorities字段
        grantedAuthoritiesConverter.setAuthorityPrefix(""); // 不添加前缀

        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);

        return jwtAuthenticationConverter;
    }
}

